package com.kuqi;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.kuqi.core.AppActivity;
import com.kuqi.core.ApplicationManager;
import com.kuqi.core.ApplicationPersistent;
import com.kuqi.entitiy.UserInfo;
import com.kuqi.http.HttpCmd;
import com.kuqi.http.HttpResponse;
import com.kuqi.utils.JsonUtil;
import com.kuqi.utils.StringHelper;
import com.kuqi.utils.UrlTool;
import java.util.Timer;
import java.util.TimerTask;

// 登录时一闪而过的检测界面， 功能如下：
// 1. 检测服务器连接状态
// 2. 检测用户登录信息（或者登录存储）
// 3. 验证用户登录信息状态
// 4. 跳转到对应的界面
public class SplashActivity extends AppActivity {

    // 定义计时跳转的计时器（网络连接）
    private Timer jumpTimer = null;

    // 定义计时跳转的计时器（数据查询）
    private Timer dataTimer = null;

    // 网络是否连接成功
    private boolean canConnectServer;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //绑定显示页面
        setContentView(R.layout.splash_page);

        // 隐藏顶部功能栏
        if(getSupportActionBar() != null){
            getSupportActionBar().hide();
        }

        //隐藏底部的导航栏
        hideVirtualKey(false);

        //设置gif显示
        ImageView gif = findViewById(R.id.load_gif);
        Glide.with(this).asGif().load(R.drawable.loading_gif).into(gif);

        // 获取当前application,并为其注册自定义Activity管理进程
        Application app = getApplication();
        Log.e("MainActivity获取成功:", app.getPackageName());
        ApplicationManager.init(app);

        // 发送检测网络连接命令
        HttpCmd cmd = new HttpCmd(handler, "", UrlTool.URL_CONNECT, ApplicationPersistent.HANDLER_KEY_CHK);
        ApplicationPersistent.getApplication().getFuncWorker().CheckHttp(cmd);

        //启动延时跳转计时器(延时3秒启动)
        jumpTimer =new Timer();
        jumpTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                timerWorker();
            }
        },3000);
    }


    /**
     * 本程序内的信息处理，只检测网络连接
     */
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == ApplicationPersistent.HANDLER_KEY_CHK) {
                canConnectServer = Boolean.parseBoolean(msg.obj.toString());
            } else if (msg.what == ApplicationPersistent.HANDLER_KEY_USER_LOGIN) { // 用户登录
                HttpResponse loginResult = JsonUtil.getInstance().fromJson(msg.obj.toString(), HttpResponse.class);
                switch (loginResult.getCode()) {
                    case 200:
                        Log.e("SearchUserInfo", "成功！");
                        UserInfo userInfo = JsonUtil.getInstance().fromJson(loginResult.getData().toString(), UserInfo.class);
                        // 查询状态置为完成
                        ApplicationPersistent.getApplication().getDataState().setUserInfoState(true);
                        // 存储状态数据
                        ApplicationPersistent.getApplication().setUserInfo(userInfo);
                        // 开始缓存查询必要的程序数据
                        startSearchDataForInit();
                        break;
                    case 400:
                        Log.e("SearchUserInfo", "失败！");
                        ApplicationPersistent.getApplication().getDataState().setUserInfoState(false);
                        break;
                    case 404:
                        Log.e("SearchUserInfo", "没有数据！");
                        ApplicationPersistent.getApplication().getDataState().setUserInfoState(false);
                        break;
                    case 301:
                        Log.e("SearchUserInfo", "密匙错误！");
                        ApplicationPersistent.getApplication().getDataState().setUserInfoState(false);
                        break;
                    case 302:
                        Log.e("SearchUserInfo", "认证过期！");
                        ApplicationPersistent.getApplication().getDataState().setUserInfoState(false);
                        break;
                    case 303:
                        Log.e("SearchUserInfo", "账号重复！");
                        ApplicationPersistent.getApplication().getDataState().setUserInfoState(false);
                        break;
                    default:
                        Log.e("SearchUserInfo", "意料之外的登录状态！");
                        ApplicationPersistent.getApplication().getDataState().setUserInfoState(false);
                        break;
                }
            }
        }
    };


    /**
     * 开始查询初始化程序必须的各种数据
     */
    private void startSearchDataForInit(){
        //启动延时跳转计时器(延时2秒启动, 每秒检测一下数据查询结果)
        dataTimer =new Timer();
        dataTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                dataWorker();
            }
        },2000, 1000);
        // 开始查询主页数据
        ApplicationPersistent.getApplication().searchHomeData();
        // 开始查询书城数据
        ApplicationPersistent.getApplication().searchStoreData();
    }


    /**
     * 计时器跳转的实际执行方法
     */
    private void timerWorker() {
        //销毁当前计时器
        jumpTimer.cancel();
        // 因为开始前已经给了3秒，如果连接不上就是连接不上了
        if (canConnectServer) { // 连接正常
            SharedPreferences preferences = getSharedPreferences("userLogin", Activity.MODE_PRIVATE);
            String applyKey = preferences.getString("applyKey", null);
            String secretKey = preferences.getString("secretKey", null);
            if(StringHelper.isNotEmpty(applyKey) && StringHelper.isNotEmpty(secretKey)){ // 存在之前的登录信息
                UserInfo user = new UserInfo(applyKey, secretKey);
                String jsonStr = JsonUtil.getInstance().toJson(user);
                HttpCmd cmd = new HttpCmd(handler, jsonStr, UrlTool.URL_LOGIN, ApplicationPersistent.HANDLER_KEY_USER_LOGIN);
                ApplicationPersistent.getApplication().getFuncWorker().SendHttp(cmd);
            }else{ // 没有之前的登录信息
                Intent intent= new Intent(SplashActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        } else { // 网络异常
            Intent intent = new Intent(SplashActivity.this, FailConnectActivity.class);
            startActivity(intent);
            finish();
        }
    }


    /**
     * 计时器检测数据加载情况执行方法
     */
    private void dataWorker(){
        boolean isAllReadyHome = ApplicationPersistent.getApplication().getDataState().checkAllReadyHome();
        boolean isAllReadyStore = ApplicationPersistent.getApplication().getDataState().checkAllReadyStore();
        if(isAllReadyHome && isAllReadyStore){ // 预查已经结束
            dataTimer.cancel();
            Intent intent= new Intent(SplashActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }else{ // 继续查询
            Log.w("CheckIfReady","数据查询尚未成功！继续等待！");
        }
        Log.w("dataWorker","#############################");
    }

}
